﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Talentnet.Core.Utilities;
using System.IO;
using Talentnet.Data.Access;
using Talentnet.Core.Utilities.Cryptophy;
using System.Collections.Generic;

public partial class consultant_ImportUsers : NormalPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
            LoadComparyList();
    }

    private void LoadComparyList()
    {
        DataTable clientList = new DataTable();
        clientList.Columns.Add("ClientID", typeof(int));
        clientList.Columns.Add("ClientName", typeof(string));
        for (int i = 2; i < 10; i++)
        {
            DataRow row = clientList.NewRow();
            row["ClientID"] = i;
            row["ClientName"] = "Company " + i.ToString();
            clientList.Rows.Add(row);
        }

        uxCompanyList.DataSource = clientList;
        uxCompanyList.DataTextField = "ClientName";
        uxCompanyList.DataValueField = "ClientID";
        uxCompanyList.DataBind();

        uxCompanyList.Items.Insert(0, new Telerik.Web.UI.RadComboBoxItem("Select One", "0"));
    }

    string _FileName = string.Empty;
    string _FolderPath = string.Empty;
    DataTable _UserList
    {
        get
        {
            if (ViewState["UserList"] != null)
                return (DataTable)ViewState["UserList"];
            //return DatabaseManager.ToDataTable(DatabaseManager.TalentnetDB.SEC_Users.Select(u => u.ClientID == Convert.ToInt32(uxCompanyList.SelectedValue)));
            return null;
            
        }
        set
        {
            ViewState["UserList"] = value;
        }
    }

    protected void ImportUserList(object sender, EventArgs e)
    {
        if (fileUserList.HasFile)
        {
            try
            {
                _FileName = Path.GetFileName(fileUserList.FileName);
                _FolderPath = Server.MapPath(@"~/App_Data/TempFiles/");
                fileUserList.SaveAs(_FolderPath + _FileName);
                CSVServices csvFile = new CSVServices() { Delimiter = CSVServices.DelimiterType.Tab, Encoding = CSVServices.EncodingType.Unicode, FileName = _FileName, FolderPath = _FolderPath };
                _UserList = csvFile.LoadCSV(-1);

                //Step1: Delete User
                int clientID = Convert.ToInt32(uxCompanyList.SelectedValue);
                //Delete roles
                IEnumerable<SEC_UsersInRole> roles = (from r in DatabaseManager.TalentnetDB.SEC_UsersInRoles
                                                      where r.SEC_User.ClientID == clientID
                                                      select r).ToList();
                DatabaseManager.TalentnetDB.SEC_UsersInRoles.DeleteAllOnSubmit(roles);
                //Delete users
                IEnumerable<SEC_User> users = (from u in DatabaseManager.TalentnetDB.SEC_Users
                                               where u.ClientID == clientID
                                               select u).ToList();
                DatabaseManager.TalentnetDB.SEC_Users.DeleteAllOnSubmit(users);
                DatabaseManager.TalentnetDB.SubmitChanges();

                //Save users list to database
                foreach (DataRow row in _UserList.Rows)
                {
                    SEC_User user = new SEC_User();
                    //Step2: Create User
                    Guid userId = Guid.NewGuid();
                    user.RecId = userId;
                    user.ClientID = clientID;
                    user.LoginName = row["UserName"].ToString();
                    user.UserNameFirst = row["FirstName"].ToString();
                    user.UserNameLast = row["LastName"].ToString();
                    string tempPwd = Common.GenPwd();
                    user.UserPassword = CryptoAgent.Current.MD5(tempPwd);
                    user.UserPasswordType = (int)SiteEnums.PasswordType.SysPwd;
                    user.Status = (byte)SiteEnums.UserStatus.WaitForActive;
                    user.Email = row["Email"].ToString();
                    user.ThemeId = SiteConstants.Talentnet.THEME_ID;
                    user.CreatedBy = userId;//SessionManager.CurrentUser.RecId;
                    user.CreatedDTS = DateTime.Now;
                    user.UserPasswordDTS = DateTime.Now;

                    DatabaseManager.TalentnetDB.SEC_Users.InsertOnSubmit(user);

                    //Step3: Assign Role for User
                    SEC_UsersInRole userInRole = new SEC_UsersInRole();
                    if(Convert.ToBoolean(row["IsManager"]))
                        userInRole.RoleId = (int)SiteEnums.UserType.Managers;
                    else
                        userInRole.RoleId = (int)SiteEnums.UserType.Employees;
                    userInRole.UserRecId = userId;
                    userInRole.CreatedDTS = DateTime.Now;
                    DatabaseManager.TalentnetDB.SEC_UsersInRoles.InsertOnSubmit(userInRole);

                    //Save User
                    DatabaseManager.TalentnetDB.SubmitChanges();
                }

                //Bind users List to grid
                grdUserList.Rebind();
                lblResult.Text = string.Empty;
            }
            catch (Exception ex)
            {
                lblResult.Text = "Import user list fail";
            }
        }

    }

    protected void grdUserList_NeedDataSource(object source, Telerik.Web.UI.GridNeedDataSourceEventArgs e)
    {
        grdUserList.DataSource = _UserList;
    }
}
